package com.settlement.system.service.impl;

import com.settlement.system.common.constant.SystemConstants;
import com.settlement.system.mapper.BsOmsOrderDetailMapper;
import com.settlement.system.model.entity.BsOmsOrder;
import com.settlement.system.mapper.BsOmsOrderMapper;
import com.settlement.system.model.entity.BsOmsOrderDetail;
import com.settlement.system.model.entity.SysStore;
import com.settlement.system.model.vo.BsOmsOrderVo;
import com.settlement.system.service.BsOmsOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.settlement.system.service.SysStoreService;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import org.springframework.util.Assert;
import com.settlement.system.common.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.settlement.system.model.query.BsOmsOrderQuery;
import com.settlement.system.model.form.BsOmsOrderForm;
import org.springframework.beans.BeanUtils;
import com.settlement.system.model.vo.BsOmsOrderImportVo;

/**
 * <p>
 * 百盛订单表 服务实现类
 * </p>
 *
 * @author huangrensen
 * @since 2024-09-04
 */
@Service
@RequiredArgsConstructor
public class BsOmsOrderServiceImpl extends ServiceImpl<BsOmsOrderMapper, BsOmsOrder> implements BsOmsOrderService {

    private final SysStoreService storeService;

    private final RedisTemplate redisTemplate;

    private final BsOmsOrderDetailMapper omsOrderDetailMapper;

    @Override
    public Page<BsOmsOrderVo> getPage(BsOmsOrderQuery queryParams) {
        // 查询参数
        int pageNum = queryParams.getPageNum();
        int pageSize = queryParams.getPageSize();
        // 拼接月份列表
        List<String> monthList = new ArrayList<>();
        String endMonthStr = queryParams.getEndMonth().replaceAll("-", "");
        LocalDate endMonth = LocalDate.parse(endMonthStr + "01", DateTimeFormatter.ofPattern("yyyyMMdd"));
        LocalDate startTime = LocalDate.parse(queryParams.getStartMonth().replaceAll("-", "") + "01", DateTimeFormatter.ofPattern(
                "yyyyMMdd"));
        // 获取已经生成的表名
        Object object = redisTemplate.opsForValue().get(SystemConstants.OMS_ORDER_KEY);
        List<String> tableNameList;
        if (object != null) {
            tableNameList = (List<String>) object;
        } else {
            tableNameList = this.baseMapper.getAllTable();
            // 添加缓存
            redisTemplate.opsForValue().set(SystemConstants.OMS_ORDER_KEY, tableNameList, 1, TimeUnit.HOURS);
        }
        // 循环追加月份
        while (!startTime.isAfter(endMonth)) {
            monthList.add(startTime.format(DateTimeFormatter.ofPattern("yyyyMM")));
            startTime = startTime.plusMonths(1);
        }
        // 根据月份判断数据库表是否存在
        List<String> existTableList = new ArrayList<>();
        String tableName;
        for (String month : monthList) {
            tableName = "bs_oms_order_%s".formatted(month);
            if (tableNameList.contains(tableName)) {
                existTableList.add(tableName);
            }
        }
        queryParams.setTableNameList(existTableList);
        // 查询数据
        Page<BsOmsOrder> page = new Page<>(pageNum, pageSize);
        Page<BsOmsOrderVo> voPage = new Page<>(pageNum, pageSize);
        if(existTableList.size() == 0){
            return voPage;
        }
        Page<BsOmsOrder> mapperPage = this.baseMapper.getPage(page, queryParams);
        BeanUtils.copyProperties(mapperPage, voPage, "records");
        List<BsOmsOrderVo> voList = new ArrayList<>();
        if(mapperPage.getRecords().size() > 0){
            SysStore store;
            BsOmsOrderVo vo;
            List<BsOmsOrderDetail> detailList;
            BsOmsOrderDetail detailQuery;
            for (BsOmsOrder record : mapperPage.getRecords()) {
                store = storeService.getByInnerSystemStoreCode(record.getStoreCode());
                vo = new BsOmsOrderVo();
                BeanUtils.copyProperties(record, vo);
                if(Objects.nonNull(store)){
                    vo.setStoreName(store.getInnerSystemStoreName());
                }
                detailQuery = new BsOmsOrderDetail();
                detailQuery.setOId(record.getId());
                detailQuery.setTableName("bs_oms_order_detail_%s".formatted(record.getId().substring(0, 6)));
                if(StringUtils.hasText(this.baseMapper.existTable(detailQuery.getTableName()))){
                    detailList = omsOrderDetailMapper.getList(detailQuery);
                    vo.setDetailList(detailList);
                }
                if(Objects.equals("Sent", vo.getStatus())){
                    vo.setStatus("已发货");
                }
                voList.add(vo);
            }
        }
        voPage.setRecords(voList);
        return voPage;
    }

     @Override
     public boolean saveBsOmsOrder(BsOmsOrderForm bsOmsOrderForm) {
         BsOmsOrder bsOmsOrder = new BsOmsOrder();
         BeanUtils.copyProperties(bsOmsOrderForm, bsOmsOrder);
         bsOmsOrder.setCreateTime(null);
         return this.saveOrUpdate(bsOmsOrder);
     }

     @Override
     public BsOmsOrderForm getBsOmsOrderFormData(Long id) {
         BsOmsOrder bsOmsOrder = this.getById(id);
         BsOmsOrderForm bsOmsOrderForm = new BsOmsOrderForm();
         BeanUtils.copyProperties(bsOmsOrder, bsOmsOrderForm);
         return bsOmsOrderForm;
     }

     @Override
     public boolean deleteBsOmsOrder(String ids) {
        Assert.isTrue(StringUtils.hasText(ids), "删除的数据为空");
        List<Long> idArray = Arrays.stream(ids.split(",")).map(Long::parseLong).collect(Collectors.toList());
        return this.removeByIds(idArray);
     }

    @Override
    public void importData(List<BsOmsOrderImportVo> voList)  {
        List<BsOmsOrder> bsOmsOrderList = new ArrayList<>();
        for (BsOmsOrderImportVo importVo : voList) {
            BsOmsOrder bsOmsOrder = new BsOmsOrder();
            BeanUtils.copyProperties(importVo, bsOmsOrder);
            bsOmsOrderList.add(bsOmsOrder);
        }
        this.saveOrUpdateBatch(bsOmsOrderList);
    }

    @Override
    public List<BsOmsOrderImportVo> findByIds(String idsStr) {
        if (!StringUtils.hasText(idsStr)) {
            return new ArrayList<>();
        }
        List<String> ids = Arrays.stream(idsStr.split(",")).collect(Collectors.toList());
        // 取出ID的前六位作为月份
        List<BsOmsOrder> bsOmsOrderList = new ArrayList<>();
        List<BsOmsOrderDetail> detailList = new ArrayList<>();
        List<String> monthList = Arrays.stream(idsStr.split(",")).map(id -> id.substring(0, 6)).distinct().toList();
        String tableName;
        BsOmsOrder query;
        BsOmsOrderDetail detailQuery;
        List<BsOmsOrder> list;
        List<BsOmsOrderDetail> details;
        for (String month : monthList) {
            query = new BsOmsOrder();
            tableName = "bs_oms_order_%s".formatted(month);
            query.setTableName(tableName);
            query.setIdList(ids);
            list = this.baseMapper.getList(query);
            bsOmsOrderList.addAll(list);
            // 查询明细
            tableName = "bs_oms_order_detail_%s".formatted(month);
            detailQuery = new BsOmsOrderDetail();
            detailQuery.setTableName(tableName);
            detailQuery.setOIdList(ids);
            details = omsOrderDetailMapper.getList(detailQuery);
            detailList.addAll(details);
        }
        List<BsOmsOrderImportVo> voList = new ArrayList<>();
        BsOmsOrderDetail detail;
        SysStore store;
        for (BsOmsOrder bsOmsOrder : bsOmsOrderList) {
            store = storeService.getByInnerSystemStoreCode(bsOmsOrder.getStoreCode());
            BsOmsOrderImportVo vo = new BsOmsOrderImportVo();
            BeanUtils.copyProperties(bsOmsOrder, vo);
            if(Objects.nonNull(bsOmsOrder.getOrderDate())){
                vo.setOrderDate(bsOmsOrder.getOrderDate().toString().replace("T", " "));
            }
            if(Objects.nonNull(bsOmsOrder.getPayDate())){
                vo.setPayDate(bsOmsOrder.getPayDate().toString().replace("T", " "));
            }
            if(Objects.nonNull(bsOmsOrder.getSendDate())){
                vo.setSendDate(bsOmsOrder.getSendDate().toString().replace("T", " "));
            }
            vo.setPayAmount(bsOmsOrder.getPayAmount().toString());
            vo.setPaidAmount(bsOmsOrder.getPaidAmount().toString());
            vo.setQty(bsOmsOrder.getQty().toString());
            vo.setAmount(bsOmsOrder.getAmount().toString());
            detail = detailList.stream().filter(d -> Objects.equals(d.getOId(), bsOmsOrder.getId())).findFirst().orElse(null);
            if (Objects.nonNull(detail)) {
                BeanUtils.copyProperties(detail, vo, "qty", "amount");
                vo.setItemQty(detail.getQty().toString());
                vo.setItemAmount(detail.getAmount().toString());
                vo.setBasePrice(detail.getBasePrice().toString());
                vo.setPrice(detail.getPrice().toString());
                vo.setItemBuyerPaidAmount(detail.getBuyerPaidAmount().toString());
                vo.setItemSellerIncomeAmount(detail.getSellerIncomeAmount().toString());
            }
            vo.setStoreName(store.getInnerSystemStoreName());
            voList.add(vo);
        }
        return voList;
    }
}
